package com.cqs.leetcode.tree.BFS;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author lixqw
 * @date 2020/8/23
 */
public class PopulatingNextRightPointersinEachNode116 {

    public Node connect(Node root) {
        if (root == null) return root;
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        int size = 0;
        Node pre = null;
        Node node = null;
        while ((size = queue.size()) > 0) {
            for (int i = 0; i < size; i++) {
                node = queue.poll();
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
                if (i > 0) {
                    pre.next = node;
                }
                pre = node;
            }
        }
        return root;
    }

    public Node connect2(Node root) {
        if (root == null) return root;
        if (root.left != null) {
            connect2(root.left);
        }
        return root;
    }
}

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {
    }

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
